#include "TextWidget.h"

#include "Framework/Application.h"
#include "Font/FontSubsystem.h"

#include "Font/Font.h"
#include "Font/Glyph.h"

RTextWidget::RTextWidget()
{
}

SVec2 RTextWidget::GetTextSize()
{
    return TextArranger.GetArrangeResult().CalculateTextSize();
}

void RTextWidget::PaintSelf(uint16_t& InZOrder,const SRect& InClipArea)
{
    if(TextArranger.GetArrangeResult().GetRenderCharCount()==0)
    {
        return;
    }


    
    //  SRect(
    //     TextArranger.GetArrangeResult().WholeImageOffset+PresentAbsPosition
    //     ,TextArranger.GetArrangeResult().WholeImageSize
    // );
    //RenderTextWidget->TextImage=TextArranger.GetArrangeResult().WholeImage->GetRenderTexture();
    
    auto RenderTextWidget=std::make_shared<SRenderStaticTextWidget>();
    RenderTextWidget->Rect=SRect(PresentAbsPosition,PresentSize);
    RenderTextWidget->ClipRect=InClipArea;
    RenderTextWidget->ZOrder=InZOrder;
    InZOrder++;

    RenderTextWidget->TextColor= Color.Get();
    RenderTextWidget->CharTextures=TextArranger.GetArrangeResult().GetRenderCharTextures();
    RenderTextWidget->CharPositions=TextArranger.GetArrangeResult().GetCharPositions();

    PaintRenderWidget(RenderTextWidget);
}


void RTextWidget::CalculatePresentPositionAndSize()
{
    Super::CalculatePresentPositionAndSize();
    ArrangeGlyphs();
}

void RTextWidget::ArrangeGlyphs()
{
    STextArrangePapameters Params;
    Params.Font=GetRenderingFont();
    Params.FontSize=FontSize.Get();
    Params.Text=Text.Get();
    Params.Wrap=Wrap.Get();
    Params.HorizontalAlign=HorizontalAlignment.Get();
    Params.VerticalAlign=VerticalAlignment.Get();

    Params.PaintAreaSize=PresentSize;

    TextArranger.ArrangeText(Params);

}

float RTextWidget::CalculateContentWidth()
{
    return TextArranger.GetArrangeResult().CalculateTextSize().X;
}

float RTextWidget::CalculateContentHeight()
{
    return TextArranger.GetArrangeResult().CalculateTextSize().Y;
}

float RTextWidget::GetLineHeight()
{
    return GetRenderingFont()->GetLineHeight(FontSize.Get());
}

TSharedObjectPtr<RFont> RTextWidget::GetRenderingFont()
{
    auto _Font= Font.Get();
    if(!_Font)
    {
        _Font=RApplication::GetApplication()->GetSubsystem<RFontApplicationSubsystem>()->GetDefaultFont();
    }
    return _Font;
}
